package com.example.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.crypto.SecretKey;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description jwt 工具类了
 * @Author lihw
 * @Date 2023/12/28 10:00
 */
public class JwtUtil {
    // 自动生成秘钥
    private static final SecretKey secretKey = Jwts.SIG.HS256.key().build();
    // 有效期: 24h
    private static final Long EXPIRATION_TIME = 60L * 60L * 24L;

    /**
     * 生成jwt,默认过期时间 24h
     *
     * @param subject       用户主体（唯一标记）
     * @param claims        脱敏信息
     * @return
     */
    public static String createToken(String subject, Map<String, Object> claims) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expirationTime = LocalDateTime.now().plusSeconds(EXPIRATION_TIME);
        return Jwts.builder()
                .claims(claims)
                .subject(subject)
                .issuedAt(Timestamp.valueOf(now))
                .expiration(Timestamp.valueOf(expirationTime))
                .signWith(secretKey, Jwts.SIG.HS256)
                .compact();
    }

    /**
     * 解析token  【解析失败返回 null】
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        try {
            Claims payload = Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
            return payload;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "lhw");
        map.put("age", "20");
        String token = createToken("李洪伟", map);
        // String token = createToken("李洪伟", map);
        System.out.println(token);
        Claims claims = parseToken(token);
        if (claims == null) {
            System.out.println("token解析失败");
        } else {
            System.out.println(claims);
        }
    }


}
